package com.zx.stock.service.impl;

import com.zx.stock.common.Const;
import com.zx.stock.entity.Stock;
import com.zx.stock.entity.StockAgency;
import com.zx.stock.entity.StockSearch;
import com.zx.stock.exception.ChildThreadException;
import com.zx.stock.mapper.StockAgencyMapper;
import com.zx.stock.mapper.StockSearchMapper;
import com.zx.stock.parallel.MultiParallelThreadHandler;
import com.zx.stock.parallel.MultiThreadHandler;
import com.zx.stock.service.StockSearchService;
import com.zx.stock.service.StockService;
import com.zx.stock.thread.AgencyThread;
import com.zx.stock.utils.HttpsUtil;
import com.zx.stock.utils.JSONUtil;
import com.zx.stock.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.*;

@Slf4j
@Service
public class StockSearchServiceImpl implements StockSearchService {

    private static final String stock_url = "http://stock.finance.qq.com/sstock/list/view/dadan.php?t=js&c=sz%s&max=80&p=1&opt=10&o=0";

    @Resource
    private StockSearchMapper stockSearchMapper;

    @Resource
    private StockService stockService;

    @Resource
    private StockAgencyMapper stockAgencyMapper;

    @Override
    public void analyze(){

        List<Stock> list = stockService.getStockList();
        //List<Stock> list = stockService.findByCategory("rise");
        if (list!=null && !list.isEmpty()){

            List<StockSearch> rsList = new ArrayList<>();

            for(Stock item:list){
                StockSearch entity = analyzeStock(item);
                if (entity!=null){
                    rsList.add(entity);
                }
            }

            if (rsList!=null && !rsList.isEmpty()){
                if(stockSearchMapper.insertBatch(rsList)>0){
                    log.info("批量新增成功");
                }else{
                    log.error("批量新增失败");
                }
            }else{
                log.info("未找到可用的stock");
            }

        }

        //var v_dadan_data_sz300131=
    }

    @Override
    public StockSearch findByCode(String code){
        Stock entity = new Stock();
        entity.setId(1);
        entity.setCode(code);
        entity.setName("");
        return analyzeStock(entity);
    }

    private StockSearch analyzeStock(Stock entity){
        String url = String.format(stock_url,entity.getCode());
        Map<String,String> headerMap = new HashMap<>();
        headerMap.put("Content-type","application/json");
        String jsonStr = HttpsUtil.doGet(url,headerMap);
        if (!StringUtil.isEmpty(jsonStr)){

            String key = String.format("v_dadan_data_sz%s",entity.getCode());
            String minuteContent = invokeFunction(key,jsonStr);
            if (!StringUtil.isEmpty(minuteContent)){
                String[] arr = minuteContent.trim().split("\\^");
                List<String> buyList = new ArrayList<>();
                List<String> sellList = new ArrayList<>();

                float sellTotal = 0;
                float buyTotal = 0;
                for (String item:arr){
                     // 13943~15:00:05~11.06~26430~2923.149~S
                    String[] itemArr = item.split("~");
                    if (itemArr.length>=6){
                        String last = itemArr[itemArr.length-1];

                        Integer total = Integer.valueOf(itemArr[3]);
                        if (last.equals("S")){ //卖
                            if (total.intValue()>=1000) {
                                sellList.add("时间:" + itemArr[1] + ",价格:" + itemArr[2] + ",数量:" + itemArr[3]);
                                sellTotal += Float.valueOf(itemArr[3]);
                            }
                        }else if (last.equals("B")){ //买

                            if (total.intValue()>=1000){
                                buyList.add("时间:"+itemArr[1]+",价格:"+itemArr[2]+",数量:"+itemArr[3]);
                                buyTotal += Float.valueOf(itemArr[3]);
                            }

                        }
                    }
                }
                if (buyList.size() < 10){
                    return null;
                }
                StockSearch stockSearch = new StockSearch();
                stockSearch.setStockId(entity.getId());
                stockSearch.setBuy(JSONArray.fromObject(buyList).toString());
                stockSearch.setBuyTotal(buyTotal);
                stockSearch.setSell(JSONArray.fromObject(sellList).toString());
                stockSearch.setSellTotal(sellTotal);
                stockSearch.setCtime(new Date());
                stockSearch.setStatus("y");
                return stockSearch;
            }

        }

        return null;
    }

    private String invokeFunction(String key,String content)  {
        try {

            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            String scriptText = String.format("function greet() { if(%s && %s.length>=2){return %s[1];} return \"\";}",key,key,key);
            engine.eval(content+scriptText);
            Invocable invocable = (Invocable) engine;
            Object object=invocable.invokeFunction("greet", "");
            log.info("解析结果:{}",object.toString());
            return object.toString();

        }catch (Exception ex){
            ex.printStackTrace();
            return "";
        }

    }

    @Override
    public void searchIcbcAgency(){

        Map<String,Object> params = new HashMap<>();
        params.put("status", Const.N);
        List<StockAgency> list = stockAgencyMapper.list(params);
        if (list!=null && !list.isEmpty()){


            int total = list.size();//总数
            int column = 500; //列数
            int row = total % column ==0?total/column:(total/column)+1; //行数


            //多线程处理并发处理
            MultiThreadHandler handler = new MultiParallelThreadHandler();


            for (int i=0;i<row;i++){
                List<StockAgency> itemList = new ArrayList<>();
                for (int j=0;j<column;j++){
                    int index = i*column+j;
                    if (index<total){
                        itemList.add(list.get(index));
                    }else{
                        break;
                    }
                }

                AgencyThread advanceConfigThread = new AgencyThread(itemList,stockAgencyMapper);
                handler.addTask(advanceConfigThread);
            }
            try {
                handler.run();
            } catch (ChildThreadException e) {
                log.info(e.getAllStackTraceMessage());
            }


            /**
            List<Stock> rsList = new ArrayList<>();
            for(Stock item:list){
                boolean success= findByIcbc(item);
                if (success){
                    rsList.add(item);
                }
            }
            for (Stock st:rsList){
                log.info("code:{},name={},\n",st.getCode(),st.getName());
            }
             **/
        }
    }

    private boolean findByIcbc(Stock entity){
        //String url = String.format("http://data.eastmoney.com/zlsj/detail/%s.html",entity.getCode());
       // String jsonStr = HttpsUtil.doGet(url);


        /**
         best of me  14:44:52
         var paramobj = {
         SHType: "0",
         SHCode: "",
         SCode: "300110",
         ReportDate: "2020-11-04",
         sortField: "SHCode",
         sortDirec: 1,
         pageNum: 1,
         pageSize: 30,
         };
         */
        String url = "http://data.eastmoney.com/dataapi/zlsj/detail";



        Map<String,Object> params = new HashMap<>();
        params.put("SHType","0");
        params.put("SHCode","");
        params.put("SCode",entity.getCode());
        params.put("ReportDate","2020-11-04");
        params.put("sortField","SHCode");
        params.put("sortDirec","1");
        params.put("pageNum","1");
        params.put("pageSize","30");
        String jsonStr = HttpsUtil.doPostHttpJson(url,null, JSONUtil.mapToJson(params));
        log.info("请求结果:{}",jsonStr);
        if (!StringUtil.isEmpty(jsonStr) && jsonStr.contains("工商")){
            return true;
        }
        return false;

    }
}
